<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rule="formRules"
    class="login-form"
    :label-col="labelCol"
  >
    <a-typography-text strong id="title">注册</a-typography-text>
    <a-form-item
      has-feedback
      label="用户名"
      name="username"
      :rules="formRules.checkNull"
    >
      <a-input
        v-model:value="formState.username"
        autocomplete="off"
        placeholder="请输入用户名"
        class="a-input"
      >
        <template #prefix>
          <UserOutlined />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      has-feedback
      label="昵称"
      name="nickname"
      :rules="formRules.checkNull"
    >
      <a-input
        v-model:value="formState.nickname"
        autocomplete="off"
        placeholder="请输入昵称"
        class="a-input"
      >
        <template #prefix>
          <NumberOutlined />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      has-feedback
      label="手机号"
      name="phone"
      :rules="formRules.checkPhone"
    >
      <a-input
        v-model:value="formState.phone"
        autocomplete="off"
        placeholder="请输入手机号"
        class="a-input"
      >
        <template #prefix>
          <PhoneOutlined />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      has-feedback
      label="邮箱"
      name="email"
      :rules="formRules.checkEmail"
    >
      <a-input
        v-model:value="formState.email"
        autocomplete="off"
        placeholder="请输入邮箱"
        class="a-input"
      >
        <template #prefix>
          <MailOutlined />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      has-feedback
      label="密码"
      name="password"
      :rules="formRules.checkNull"
    >
      <a-input-password
        v-model:value="formState.password"
        autocomplete="off"
        placeholder="请输入密码"
        class="a-input"
      >
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item
      has-feedback
      label="确认密码"
      name="checkPassword"
      :rules="formRules.checkPassword"
    >
      <a-input-password
        v-model:value="formState.checkPassword"
        autocomplete="off"
        placeholder="请确认输入密码"
        class="a-input"
      >
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item>
      <a-button
        type="primary"
        :loading="isLoading"
        @click="submitForm"
        id="login-button"
        >提交</a-button
      >
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  UserOutlined,
  LockOutlined,
  NumberOutlined,
  PhoneOutlined,
  MailOutlined,
} from "@ant-design/icons-vue";
import type { FormInstance } from "ant-design-vue";
import type { Rule } from "ant-design-vue/es/form";
import { message } from "ant-design-vue";
import { useLoginStore } from "../store/loginStore";
import { HTTP_STATUS } from "../api/request";

const loginStore = useLoginStore();

interface FormState {
  username: string;
  nickname: string;
  phone: string;
  email: string;
  password: string;
  checkPassword: string;
}

const formState = ref<FormState>({
  username: "",
  nickname: "",
  phone: "",
  email: "",
  password: "",
  checkPassword: "",
});

const formRef = ref<FormInstance>();

//按钮加载状态
const isLoading = ref<boolean>(false);

const labelCol = { style: { width: "80px" } };

//提交表单
function submitForm() {
  formRef.value
    ?.validate()
    .then((valid) => {
      if (valid) {
        isLoading.value = true;
        setTimeout(async () => {
          try {
            const res = await loginStore.requestRegister({
              username: formState.value.username,
              nickname: formState.value.nickname,
              phone: formState.value.phone,
              email: formState.value.email,
              password: formState.value.password,
            });
            if (res.status == HTTP_STATUS.SUCCESS) {
              message.success("注册成功")
              formRef.value?.resetFields()
            }
          } catch (error) {
          } finally {
            isLoading.value = false;
          }
        });
      }
    })
    .catch(() => {
      message.error("注册失败，请检查输入信息是否正确");
      isLoading.value = false;
    });
}

//验证不为空
const validateBlank = async (_rule: Rule, value: string) => {

  if (value === "" || /^\s*$/.test(value)) {
    return Promise.reject("不能为空");
  } else if (value.includes(" ")) {
    return Promise.reject("不能包含空格");
  }
  // callback()
  return Promise.resolve();
};

const validatePhone = async (_rule: Rule, value: string) => {
  try {
    await validateBlank(_rule,value)
  } catch (error) {
    return Promise.reject(error)
  }
  if (!/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/.test(value)) {
    return Promise.reject("手机号格式不正确")
  }
  return Promise.resolve()
}

const validateEmail = async (_rule: Rule, value: string) => {
  try {
    await validateBlank(_rule,value)
  } catch (error) {
    return Promise.reject(error)
  }
  if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
    return Promise.reject("邮箱格式不正确")
  }
  return Promise.resolve()
}

//确认密码验证
const validatePassword = async (_rule: Rule, value: string) => {
  if (value !== formState.value.password) {
    return Promise.reject("密码不一致");
  }
  return Promise.resolve();
};

//配置校验规则
const formRules: Record<string, Rule[]> = {
  checkNull: [{ validator: validateBlank, trigger: "blur", required: true }],

  checkPassword: [
    { validator: validatePassword, trigger: "blur", required: true },
  ],
  checkPhone: [
    {validator: validatePhone,trigger: "blur",required: true}
  ],
  checkEmail: [
    {validator: validateEmail,trigger: "blur",required: true}
  ]
};
</script>

<style lang="scss" scoped>
.login-form {
  border: 1px solid rgba(205, 198, 198, 0.957);
  border-radius: 10px;
  width: 450px;
  box-shadow: 0px 5px 10px #cccc;
  height: 180 px;
  vertical-align: middle;
  text-align: center;
  font-weight: bolder;
  padding-left: 70px;
  /* display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  justify-content: center;
  align-items: center; */

  #title {
    font-size: large;
    display: inline-block;
    margin: {
      top: 10px;
      bottom: 10px;
    }
  }
}

.a-input {
  width: 220px;
}

#login-button {
  user-select: none;
  width: 300px;
}
</style>
